<template>
  <div class="sdy-login">
    <SdyHeader title="啥都有登录页" back></SdyHeader>
    <van-form class='login-from' @submit="submitHandler">
      <van-cell-group inset>
        <van-field
          v-model="username"
          name="用户名"
          label="用户名"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名',pattern:/\w{6,12}/ }]"
        />
        <van-field
          v-model="password"
          type="password"
          name="密码"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />
      </van-cell-group>
      <div>
        还没有账号?<router-link
         to='/register'
         >去注册</router-link>
      </div>
      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script setup lang="ts">
import {ref} from 'vue'
//导入相关api
import {loginApi} from '@/api/users'
import {Toast} from 'vant'
import {useRouter,type Router} from 'vue-router'
  const username = ref<string>('')
  const password = ref<string>('')

const $router: Router = useRouter()
  const submitHandler = async ()=>{
    const res = await loginApi(username.value,password.value)
    // console.log(res)

    //表示登录成功
    if(((res as unknown) as {code:string}).code === '200'){
    Toast({
      message:'登录成功',
    })
    //存储一下token和userId
    window.localStorage.setItem('token', res.data.token)
    window.localStorage.setItem('user_id', res.data.userid )
    setTimeout(()=>{
      //跳转的首页
      $router.push({path:'/home'})
    },1000)
    return

  }
        Toast({
      message:'登录失败'
    })  
  }
</script>

<style scoped lang="scss">
.sdy-login{
  height:100%;
  overflow:hidden;
  > .login-from{
    margin-top: 10px;
    border:1px solid rgb(233, 233, 233);
    border-radius: 10px;
  }
}
</style>
